package com.mifengkong.frwidget.banner.customerbanner;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by jiangyongxing on 2017/8/13.
 * 描述：
 */

public class RollViewPager extends ViewPager {

    private BannerAdapter mAdapter;
    private final int SCROLL_MSG = 0x0011;//发送消息的message的what
    private int mCutDoenTime = 4000;//实现自动轮播切换页面的时间
    private BannerScroller mBannerScroller;

    private List<View> mConvertViewList;
    private Activity mActivity;
    private float mMoveY;
    private float mMoveX;
    private int mTouchSlop;
    private onTouchClickListener mListener;
    private MyOnTouchListener mTouchListener;
    private boolean mIs_move;
    private int mDownX;
    private int mDownY;
    private int mCurrentPosition;
    private boolean canScroll = true;
    private boolean autoScroll = true;//是否允许自动开启滚动模式
    private BannerPagerAdapter mBannerPagerAdapter;

    public RollViewPager(Context context) {
        this(context, null);
    }

    public RollViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        try {
            Field field = ViewPager.class.getDeclaredField("mScroller");
            field.setAccessible(true);

            mBannerScroller = new BannerScroller(context);

            //第一个参数代表当前的属性在哪个类,第二个参数代表要设置的值
            field.set(this, mBannerScroller);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mConvertViewList = new ArrayList<>();
        //Distance in pixels a touch can wander before we think the user is scrolling
        mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
        // 初始化点击监听
        mTouchListener = new MyOnTouchListener();
    }

    /**
     * 设置页面切换的时间
     *
     * @param duration 时间  毫秒值
     */
    public void setScrollDuration(int duration) {
        mBannerScroller.setScrollerDuration(duration);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (mAdapter == null)
                return;
            setCurrentItem(getCurrentItem() + 1);
            startRoll();
//            FRLog.e("jiang","startroll");
        }
    };

    /**
     * 设置自定义的banner
     *
     * @param adapter
     */
    public void setAdapter(BannerAdapter adapter) {
        mAdapter = adapter;
        mBannerPagerAdapter = new BannerPagerAdapter();
        setAdapter(mBannerPagerAdapter);
        setPageTransformer(true, mAdapter.getPageTransformer());
        setOffscreenPageLimit(2);
        mActivity = (Activity) getContext();
        mActivity.getApplication().registerActivityLifecycleCallbacks(mDefalutActivityLeftcycleCallbacks);
    }

    /**
     * 实现自动轮播
     */
    public void startRoll() {
        if (null != mHandler) {
            mHandler.removeMessages(SCROLL_MSG);//清除消息

            if (!canScroll)
                return;
            mHandler.sendEmptyMessageDelayed(SCROLL_MSG, mCutDoenTime);
        }
    }

    public void setScrollStatus(boolean canScroll) {
        this.canScroll = canScroll;
    }

    private class BannerPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            //为了实现无线循环
            return mAdapter.needInfiniteLoop() ? Integer.MAX_VALUE : mAdapter.getCount();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        /**
         * 创建item的回调方法
         *
         * @param container
         * @param position
         * @return
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            //position  0->2的31次方
            View bannerItemView = mAdapter.getView(position % mAdapter.getCount(), getConvertView());
            bannerItemView.setTag(position % mAdapter.getCount());
            bannerItemView.setOnTouchListener(mTouchListener);
            container.addView(bannerItemView);
            return bannerItemView;
        }

        /**
         * 销毁item的回调方法
         *
         * @param container
         * @param position
         * @param object
         */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
            mConvertViewList.add((View) object);

        }

        @Override
        public void notifyDataSetChanged() {
            super.notifyDataSetChanged();
        }
    }

    /**
     * @return
     */
    private View getConvertView() {
        for (View view : mConvertViewList) {
            if (view.getParent() == null)
                return view;
        }
        return null;
    }

    // 初始化监听器对象
    public void setmListener(onTouchClickListener listener) {
        this.mListener = listener;
    }

    private void setCoudownTime(int millisecond) {
        this.mCutDoenTime = millisecond;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (null != mHandler) {
            mHandler.removeMessages(SCROLL_MSG);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (autoScroll) {
            startRoll();
        }
    }

    DefalutActivityLeftcycleCallbacks mDefalutActivityLeftcycleCallbacks = new DefalutActivityLeftcycleCallbacks() {
        @Override
        public void onActivityResumed(Activity activity) {
            super.onActivityResumed(activity);
            //是不是监听的加载了轮播图的Activity的生命周期
            if (activity == mActivity) {
                if (autoScroll) {
                    startRoll();
                }
            }
            //开始轮播
        }

        @Override
        public void onActivityPaused(Activity activity) {
            super.onActivityPaused(activity);
            //停止轮播
            if (activity == mActivity) {
                if (null != mHandler) {
                    mHandler.removeMessages(SCROLL_MSG);
                }
            }
        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            super.onActivityDestroyed(activity);
            if (activity == mActivity) {
                mHandler = null;
                mActivity.getApplication().unregisterActivityLifecycleCallbacks(mDefalutActivityLeftcycleCallbacks);
            }
        }
    };

    private class MyOnTouchListener implements OnTouchListener {

        private long downThreadTimeMillis;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // 停止跳动
                    if (null != mHandler) {
                        mHandler.removeMessages(SCROLL_MSG);
                    }
                    // 区分到底是长按还是单机事件
                    // 获取到当前的时间

                    downThreadTimeMillis = System.currentTimeMillis();
                    // 判断当前时间如果小于500毫秒。那么就是单机事件

                    mMoveX = event.getX();
                    mMoveY = event.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    break;
                case MotionEvent.ACTION_UP:
                    float upY = event.getY();
                    float upX = event.getX();
                    long currentThreadTimeMillis = System.currentTimeMillis();
                    if (currentThreadTimeMillis - downThreadTimeMillis < 150 && ((Math.abs(mMoveX - upX) < mTouchSlop) && (Math.abs(mMoveY - upY) < mTouchSlop))) {
                        //短按事件
                        if (mListener != null) {
                            mListener.onItemTouchClickListener(mCurrentPosition);
                        }
                        return false;
                    }
                    break;
                default:
                    break;
            }

            return true;
        }
    }

    /**
     * 事件分发
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {
            case MotionEvent.ACTION_MOVE:

                int currentX = (int) ev.getX();
                int currentY = (int) ev.getY();

                if (Math.abs(currentX - mDownX) > Math.abs(currentY - mDownY)) {
                    // 请求父类不要拦截子类
                    // getParent()获取到父类
                    mIs_move = false;
                } else {
                    mIs_move = true;
                }
                break;
            case MotionEvent.ACTION_DOWN:
                mDownX = (int) ev.getX();
                mDownY = (int) ev.getY();
                mIs_move = false;
                break;
            case MotionEvent.ACTION_UP:
                if (autoScroll) {
                    startRoll();
                }
                break;
        }
        getParent().requestDisallowInterceptTouchEvent(!mIs_move);
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (!canScroll)
            return false;
        return super.onInterceptTouchEvent(ev);
    }

    public void setCurrentPosition(int position) {
        mCurrentPosition = position;
    }

    public void setCanAutoScroll(boolean autoScroll) {
        this.autoScroll = autoScroll;
    }

    public void refreshView(int position, View view) {
        getAdapter().notifyDataSetChanged();
    }
}